#!/usr/bin/env ruby

# This may be the most fragile build script ever written.

require 'open3'

def pipe(text, *cmds)
    cmds.each {|c|
        text = Open3.popen3(c) {|i,o|
            i.puts(text); i.close
            o.read
        }
    }
    text
end


# Get the code and do ridiculous preprocessing on it.
code = File.read('js/html.js')

code.sub!('/* INSERT_CSS_HERE */', pipe(File.read('css/gif-sound.css'), 'java -jar utils/yuicompressor-2.4.7/build/yuicompressor-2.4.7.jar --type css'))
code.sub!('// INSERT_GIF_JS_HERE', File.read('js/gif.js'))

code.gsub!(/BEGIN_NON_BOOKMARKLET_CODE.*?END_NON_BOOKMARKLET_CODE/m, '')

# Compile the code, and put it through yui-compressor, too, to get rid of the newlines.
code = pipe(code, 'java -jar utils/closure/compiler.jar --compilation_level  SIMPLE_OPTIMIZATIONS --warning_level VERBOSE --jscomp_off=checkVars',
                  'java -jar utils/yuicompressor-2.4.7/build/yuicompressor-2.4.7.jar --type js')

# To get rid of the stupid global scope.
code.sub!(/^([^(]*)(\(function\(\)\{)/, '\2\1')

# Bookmarklet-ready.
code = 'javascript:' + code

# Oh, I guess I need to escape the HTML too.
#code = CGI.escape(code) # Hah!
code = code.gsub('%', '%25') # '&amp;'
code = code.gsub('&', '%26')
code = code.gsub("'", '%27')
#code = code.gsub('"', '%27') # The bookmarklet is embedded in single quotes in the HTML page, so I don't need to worry about double-quotes; maybe I should escape them anyway?

# Now it's ready.
print code
